package com.ly.demo;

import com.ly.demo.bean.Options;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @program: ly-common
 * @description:
 * @author: 作者
 * @create: 2022-08-21 16:45
 */
@Configuration
@ComponentScan("com.ly.demo")
public class DemoConfig implements WebMvcConfigurer {

    @Resource
    private Options options;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (options.getResMap() == null) {
            return;
        }
        options.getResMap().forEach((w, d) -> {
            if ("root".equalsIgnoreCase(w)) {
                w = "/";
            }
            w = setPath(w) + "**";
            d = "file:" + setPath(d);
            System.out.println("DemoConfig.静态资源映射:" + w + " ==> " + d);
            registry.addResourceHandler(w).addResourceLocations(d);
        });
    }

    private String setPath(String path) {
        if (path.startsWith("/") == false) {
            path = "/" + path;
        }
        if (path.endsWith("/") == false) {
            path += "/";
        }
        return path;
    }
}
